<template>
  <div class="container">
    <el-dialog
      :title="this.articleData.id ? '修改' : '添加'"
      :visible="addDialogVisible"
      @close="closeDialog"
      @open="openDialog"
    >
      <!-- 表单 -->
      <el-form
        ref="addForm"
        label-width="120px"
        :model="articleData"
        :rules="rules"
      >
        <el-form-item label="文章标题:" prop="title">
          <el-input v-model="articleData.title" placeholder="请输入文章标题" />
        </el-form-item>
        <el-form-item label="文章内容:" prop="articleBody" >
          <!-- 富文本编辑器 -->
          <quill-editor
            :options="editorOption"
            v-model="articleData.articleBody"
            @blur='question'
          >
          </quill-editor>
        </el-form-item>
        <el-form-item label="视频地址:">
          <el-input v-model="articleData.videoURL" placeholder="请输入视频地址" />
        </el-form-item>
      </el-form>
      <!-- footer插槽 -->
      <template #footer>
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { add, update } from '@/api/hmmm/articles.js'
export default {
  name: 'ArticlesAdd',
  data () {
    return {
      articleData: { title: '', articleBody: '', videoURL: '' },
      rules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' }
        ],
        articleBody: [
          { required: true, message: '请输入文章内容', trigger: 'blur' }
        ]
      },
      editorOption: {
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
            ['blockquote', 'code-block'], // 引用，代码块
            ['image', 'link'] // 上传图片、上传视频
          ]
        }
      }
    }
  },
  props: {
    addDialogVisible: {
      required: true
    },
    value: {
      default: {}
    }
  },
  methods: {
    question () {
      this.$refs.addForm.validateField('articleBody')
    },
    confirm () {
      this.$refs.addForm.validate(async valid => {
        if (valid) {
          if (!this.articleData.id) {
            // 新增
            await add(this.articleData)
          } else {
            // 修改
            await update(this.articleData)
          }
          // 提示：添加成功
          this.$message.success(this.articleData.id ? '修改成功' : '添加成功')
          // 调用父组件的方法，渲染页面
          this.$parent.getArticleList()
          // 通知父组件关对话框
          this.closeDialog()
        }
      })
    },
    cancel () {
      this.closeDialog()
    },
    openDialog () {
      this.articleData = this.value
    },
    closeDialog () {
      // 通知父组件，关闭对话框
      this.$emit('closeDialog')
      // 重置表单
      this.$refs.addForm.resetFields()
      this.articleData = {}
    }
  }
}
</script>

<style scoped lang='scss'>
  ::v-deep .el-dialog{
    width:70%
  }
  ::v-deep .quill-editor .ql-container {
    height: 200px;
  }
</style>
